import java.io.*;
import java.util.*;
class AveragePriceCalculator {
    public static void main(String[] args) {
        File inputFile = new File("C:\\Users\\73880\\Desktop\\商品列表.txt"); // 假设文件名为商品列表.txt
        File outputFile = new File("C:\\Users\\73880\\Desktop\\商品列表_带行号.txt"); // 输出文件，包含行号
        double sum = 0;
        int count = 0;
        try (Scanner sc = new Scanner(inputFile);
             PrintWriter pw = new PrintWriter(new FileWriter(outputFile));
             PrintWriter appendPw = new PrintWriter(new FileWriter(inputFile, true))) { // 以追加模式打开原文件
            int lineNumber = 1;
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                // 添加行号并写入新文件
                pw.println(lineNumber++ + ": " + line);
                // 解析价格数据
                if (line.contains(",")) {
                    String[] parts = line.split(",");
                    String pricePart = parts[1].trim();
                    // 提取价格数字
                    String price = pricePart.replaceAll("[^\\d.]", ""); // 使用正则表达式去掉所有非数字字符
                    try {
                        double priceValue = Double.parseDouble(price);
                        sum += priceValue;
                        count++;
                    } catch (NumberFormatException e) {
                        System.out.println("无法解析的价格: " + pricePart);
                    }
                }
            }
            // 计算平均价格
            double averagePrice = count > 0 ? sum / count : 0;
            String formattedAveragePrice = String.format("%.2f元/台", averagePrice);

            // 将平均价格追加到原文件末尾
            appendPw.println("平均价格: " + formattedAveragePrice);

            System.out.println("平均价格: " + formattedAveragePrice);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

